package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.ForumFavoriteDTO;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.ForumFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/forum/favorite")
public class ForumFavoriteController {
    @Autowired
    private ForumFavoriteService forumFavoriteService;

    /**
     * 收藏帖子
     */
    @PostMapping("/favorite")
    public CommonResponse<Boolean> favorite(@RequestParam Integer userId, @RequestParam Integer postId) {
        try {
            boolean result = forumFavoriteService.favorite(userId, postId);
            return CommonResponse.success(result);
        } catch (Exception e) {
            return CommonResponse.error("收藏失敗：" + e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @PostMapping("/unfavorite")
    public CommonResponse<Boolean> unfavorite(@RequestParam Integer userId, @RequestParam Integer postId) {
        try {
            boolean result = forumFavoriteService.unfavorite(userId, postId);
            return CommonResponse.success(result);
        } catch (Exception e) {
            return CommonResponse.error("取消收藏失敗：" + e.getMessage());
        }
    }

    /**
     * 查詢是否收藏
     */
    @GetMapping("/isFavorited")
    public CommonResponse<Boolean> isFavorited(@RequestParam Integer userId, @RequestParam Integer postId) {
        try {
            boolean result = forumFavoriteService.isFavorited(userId, postId);
            return CommonResponse.success(result);
        } catch (Exception e) {
            return CommonResponse.error("查詢收藏狀態失敗：" + e.getMessage());
        }
    }

    /**
     * 查詢用戶收藏列表
     */
    @GetMapping("/user/{userId}")
    public CommonResponse<List<ForumFavoriteDTO>> getFavoritesByUser(@PathVariable Integer userId) {
        try {
            List<ForumFavoriteDTO> favorites = forumFavoriteService.getFavoritesByUser(userId);
            return CommonResponse.success(favorites);
        } catch (Exception e) {
            return CommonResponse.error("查詢收藏列表失敗：" + e.getMessage());
        }
    }

    /**
     * 查詢帖子被收藏數
     */
    @GetMapping("/count/{postId}")
    public CommonResponse<Integer> getFavoriteCountByPost(@PathVariable Integer postId) {
        try {
            int count = forumFavoriteService.getFavoriteCountByPost(postId);
            return CommonResponse.success(count);
        } catch (Exception e) {
            return CommonResponse.error("查詢收藏數失敗：" + e.getMessage());
        }
    }
} 